package com.syl.starter.itools.framework.utils;

import com.syl.starter.itools.base.constants.BaseConstant;
import com.syl.starter.itools.common.utils.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * request工具类
 *
 * @author syl
 * @create 2018-10-24 15:56
 **/
public class RequestUtils {
    private static final String URL_PARAM_SPLIT_1 = "[&]";
    private static final String URL_PARAM_SPLIT_2 = "[=]";

    /**
     * 从request中获取body
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestBody(HttpServletRequest request) throws IOException {
        return RequestUtils.getRequestBody(request, String.class);
    }

    /**
     * 从request中获取body并转换为Map对象
     * @param request
     * @return
     * @throws IOException
     */
    public static Map<String, String> getRequestBodyToMap(HttpServletRequest request) throws IOException {
        return RequestUtils.getRequestBody(request, Map.class);
    }

    /**
     * 从request中获取body 并转换为任意对象
     * @param request
     * @param cz 返回对象类型
     * @return
     * @throws IOException
     */
    public static <T> T getRequestBody(HttpServletRequest request, Class<T> cz) throws IOException {
        BufferedReader reader = request.getReader();
        String str = "";
        String json = "";
        while ((str = reader.readLine()) != null) {
            json += str;
        }
        if (cz == null || cz == String.class) return (T) json;
        return JsonUtils.fromJson(json, cz);
    }

    /**
     * 解析url参数中的键值对
     * @param param
     * @return
     */
    public static Map<String, String> URLParamParse(String param) {
        Map<String, String> mapRequest = new HashMap();
        String[] arrSplit;
        String strUrlParam = param;
        if (strUrlParam == null) {
            return mapRequest;
        }
        arrSplit = strUrlParam.split(URL_PARAM_SPLIT_1);
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual;
            arrSplitEqual = strSplit.split(URL_PARAM_SPLIT_2);
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (StringUtils.isNotEmpty(arrSplitEqual[0])) {
                    //只有参数没有值
                    mapRequest.put(arrSplitEqual[0], BaseConstant.EMPTY_STRING);
                }
            }
        }
        return mapRequest;
    }

    /**
     * mvc 中全局获取 request
     * @return
     */
    public static HttpServletRequest getRequest(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if(attributes == null)
            return null;
        return ((ServletRequestAttributes)attributes).getRequest();
    }

    /**
     * mvc 中全局获取 response
     * @return
     */
    public static HttpServletResponse getResponse(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if(attributes == null)
            return null;
        return ((ServletRequestAttributes)attributes).getResponse();
    }

    /**
     * mvc 中全局获取session
     * @return
     */
    public static HttpSession getSession(){
        HttpServletRequest request = getRequest();
        return request.getSession();
    }

    /**
     * mvc 中全局获取sessionId
     * @return
     */
    public static String getSessionId(){
        return getSession().getId();
    }

    /**
     * 获取基础路径 例如 http://www.baidu.com:8080/example/
     * @return
     */
    public static String getBasePath(){
        HttpServletRequest request = getRequest();
        String path = request.getContextPath();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    }

    /**
     * 获取网站域名
     * @return
     */
    public static String getDomain(){
        HttpServletRequest request = getRequest();
        return request.getServerName();
    }

    /**
     * 获得客户端IP地址  当使用了nginx反向代理后会失效
     *
     * @return
     */
    @Deprecated
    public static String getClientIP(){
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
